package com.sdms.core.auth;

import com.sdms.core.SupportedOperation;
import com.sdms.core.login.SessionStore;
import com.sdms.core.login.UserSession;
import com.sdms.core.rbac.Role;

public class AuthoriseServiceImpl implements IAuthoriseService
{
	@Override
	public void authoriseUser( String sessionId, SupportedOperation op ) throws UnauthorisedUserException
	{
		UserSession userSession = SessionStore.retrieveSession( sessionId );
		if ( userSession != null )
		{
			Role userRole = userSession.getRole();
			if ( userRole.getAssignedRights().contains( op.getRight() ) || ( userRole.isUpgraded() && userRole.getUpgradeRights().contains( op.getRight() ) ) )
			{
				Priviledges.setNewPriviledge( op.getRight() );
			}
			else
			{
				String errorMsg = "Unauthorised access detected";
				throw new UnauthorisedUserException( errorMsg );
			}
		}
		else
		{
			String errorMsg = "Invalid user session";
			throw new UnauthorisedUserException( errorMsg );
		}
	}

	@Override
	public void clearPriviledges()
	{
		Priviledges.clearPriviledges();
	}

	@Override
	public void clearExistingPreviousPriviledgesAddNewPriviledges( SupportedOperation op )
	{
		Priviledges.clearPriviledges();
		Priviledges.setNewPriviledge( op.getRight() );
	}

	@Override
	public void changeUserPriviledges( String sessionId ) throws UnauthorisedUserException
	{
		UserSession userSession = SessionStore.retrieveSession( sessionId );
		if ( userSession != null )
		{
			Role userRole = userSession.getRole();
			if ( userRole.getAssignedRights().contains( SupportedOperation.CHANGE_PREVILAGE.getRight() ) )
			{
				if ( userRole.isUpgraded() )
				{
					userRole.setUpgraded( false );
				}
				else
				{
					userRole.setUpgraded( true );
				}
			}
			else
			{
				String errorMsg = "Unauthorised access detected";
				throw new UnauthorisedUserException( errorMsg );
			}
		}
		else
		{
			String errorMsg = "Invalid user session";
			throw new UnauthorisedUserException( errorMsg );
		}
	}
}
